package jvm;

import java.util.concurrent.RecursiveTask;

/**
 * @author Europa
 * @create 2020-05-31 19:09
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private final long start;
    private final long end;

    public ForkJoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Long compute() {
        long criticality = 1000000;
        if ((end - start) < criticality) {
            long value = 0;
            for (long i = start; i <= end; i++) {
                value += i;
            }
            return value;
        }
        //forkjoin递归
        long mid = (start + end) / 2;
        ForkJoinDemo demo = new ForkJoinDemo(start, mid);
        //拆分任务,把任务压入线程队列
        demo.fork();
        ForkJoinDemo demo1 = new ForkJoinDemo(mid + 1, end);
        demo1.fork();
        return demo.join() + demo1.join();
    }
}
